import { defineConfig, loadEnv } from "vite"
import Uni from "@dcloudio/vite-plugin-uni"
import UniPages from '@uni-helper/vite-plugin-uni-pages'
import Components from '@uni-helper/vite-plugin-uni-components'
import { WotResolver } from '@uni-helper/vite-plugin-uni-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
import UnoCSS from 'unocss/vite'
import path from 'path'

// https://vitejs.dev/config/
export default ({ mode }) => {
	const env = loadEnv(mode, path.resolve(process.cwd(), 'env'))
	console.log('env -> ', env)
	console.log('process.env.UNI_PLATFORM: ', process.env.UNI_PLATFORM) 

	return defineConfig({
    envDir: './env',
    plugins: [
      Components({
        resolvers: [WotResolver()]
      }), 
      UniPages(),
      Uni(),
      UnoCSS(),
      AutoImport({
      	imports: ['vue', 'pinia', 'uni-app'],
      	dts: 'src/auto-import.d.ts',
      	eslintrc: { enabled: false },
      	vueTemplate: true,
      })
    ],
     build: {
        sourcemap: false,
        chunkSizeWarningLimit: 1500,
        rollupOptions: {
          output: {
            chunkFileNames: 'assets/js/[name]-[hash].js',
            entryFileNames: 'assets/js/[name]-[hash].js',
            assetFileNames: 'assets/[ext]/[name]-[hash][extname]',
            manualChunks(id) {
              if (id.includes('node_modules')) {
                return id.toString().split('node_modules/')[1].split('/')[0].toString()
              }
            }
          }
        }
      },
    resolve: {
      alias: {
        '@': path.join(process.cwd(), './src'),
        '@img': path.join(process.cwd(), './src/static/images'),
      }
    },
    server: {
      host: '0.0.0.0',
      hmr: true,
      port: 5173,
      proxy: {
        '/cloud': {
          target: 'http://127.0.0.1:8800/cloud/',
          ws: true,
          secure: true,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/cloud/, ''),
        }
      }
    },
  });
}
